//
//  MBHomeMainController.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/2/15.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBHomeMainController.h"
#import "MBUserCenterController.h"
#import "JXCategoryView.h"
#import "JXCategoryListContainerView.h"
#import <ViewDeck/ViewDeck.h>
#import "MBHomeWaterfallController.h"
#import "MBShortVideoController.h"
#import "MBRightNavPullMenuView.h"
#import "ZJScrollPageView.h"
#import "MBHomeAttentionController.h"
#import "MBHomeLocalController.h"
#import "MBHomeLiveController.h"
#import "MBHomeFindController.h"
#import "MBLocation.h"
#import "MBLiveMainController.h"
#import "MBStartLiveController.h"
#import "MBQiNiuUpTokenModel.h"
#import "MBLoginController.h"
#import "MBTradeid.h"
#import "MBShortVideoPublishController.h"


@interface MBHomeMainController ()<JXCategoryViewDelegate,JXCategoryListContainerViewDelegate,ZJScrollPageViewDelegate>
@property(nonatomic, strong)UIButton *leftNavButton;
@property(nonatomic, strong)UIButton *rightNavButton;
@property(nonatomic, strong)NSArray  *titleArray;
@property(nonatomic, strong)MBRightNavPullMenuView *menuView;
@property(strong, nonatomic)NSArray<NSString *> *titles;
@property(strong, nonatomic)NSArray<UIViewController<ZJScrollPageViewChildVcDelegate> *> *childVcs;
@property (weak, nonatomic) ZJScrollSegmentView *segmentView;
@property (weak, nonatomic) ZJContentView *contentView;
@property (nonatomic, assign)BOOL isLogin;
@end

@implementation MBHomeMainController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self createCustomNav];
    [[MBLocation shareMBLocation] startLocation];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(LoginState:) name:MBIsLoginNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CancelLogin:) name:CancelLoginNotificationKey object:nil];

}

/**
 判读用户时候有直播权限
 */
-(void)checkLiveiLimits {
    NSDictionary *param = @{
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId),
                            @"ruleId":@"1" //写死1
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kHome_live_limits setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBStartLiveController *vc = [[MBStartLiveController alloc]init];
        [weakself.navigationController pushViewController:vc animated:YES];
//       
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

-(void)createUI {
//    JXCategoryTitleView *titleView = [[JXCategoryTitleView alloc]initWithFrame:(CGRect){{0,0},{250,44}}];
//    titleView.delegate = self;
//    self.navigationItem.titleView = titleView;
//    titleView.titles = self.titleArray;
//    titleView.titleColorGradientEnabled = NO;
//    titleView.titleColor = Color_666666;
//    titleView.titleSelectedColor = Color_FF8000;
//    titleView.titleFont = kFont(14);
//    titleView.titleLabelZoomEnabled = YES;
//    titleView.titleLabelZoomScale = 1.2;
//
//    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
//    lineView.indicatorLineWidth = 40;
//    lineView.indicatorLineViewColor = Color_FF8000;
//    lineView.indicatorLineViewHeight = 3.0f;
//    titleView.indicators = @[lineView];
//
//    JXCategoryListContainerView *contentViw = [[JXCategoryListContainerView alloc]initWithDelegate:self];
//    contentViw.frame = self.view.frame;
//    [self.view addSubview:contentViw];
//    titleView.contentScrollView = contentViw.scrollView;
    self.childVcs = [self setupChildVC];
    [self setupSegmentView];
    [self setupContentView];
    [self.segmentView setSelectedIndex:1 animated:YES];
}


-(void)createCustomNav {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightNavButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.leftNavButton];
    self.navigationItem.title = @"";
}

-(NSArray *)setupChildVC {
    MBHomeAttentionController *attentionVC = [[MBHomeAttentionController alloc]init];
    MBHomeFindController *findVC = [[MBHomeFindController alloc]init];
    MBHomeLocalController *localVC = [[MBHomeLocalController alloc]init];
    MBHomeLiveController *liveVC = [[MBHomeLiveController alloc]init];
    NSArray *vcArray = @[attentionVC,findVC,localVC,liveVC];
    return vcArray;
}

-(void)setupSegmentView {
    ZJSegmentStyle *style = [[ZJSegmentStyle alloc] init];
    style.showLine = YES;
    style.scrollLineColor = Color_FF8000;
    style.titleFont = kMFont(14);
    style.titleBigScale = 1.2;
    style.normalTitleColor = Color_666666;
    style.selectedTitleColor = Color_FF8000;
    // 不要滚动标题, 每个标题将平分宽度
    style.scrollTitle = YES;
    style.adjustCoverOrLineWidth = YES;
    style.titleMargin = 30.0f;
    self.titles = self.titleArray;
    
    // 注意: 一定要避免循环引用!!
    __weak typeof(self) weakSelf = self;
    ZJScrollSegmentView *segment = [[ZJScrollSegmentView alloc] initWithFrame:CGRectMake(0, 64.0, 260.0, 28.0) segmentStyle:style delegate:self titles:self.titles titleDidClick:^(ZJTitleView *titleView, NSInteger index) {
        [weakSelf.contentView setContentOffSet:CGPointMake(weakSelf.contentView.bounds.size.width * index, 0.0) animated:YES];
        
    }];
    // 当然推荐直接设置背景图片的方式
    //    segment.backgroundImage = [UIImage imageNamed:@"extraBtnBackgroundImage"];
    self.segmentView = segment;
    self.navigationItem.titleView = self.segmentView;
}

-(void)setupContentView {
    ZJContentView *content = [[ZJContentView alloc] initWithFrame:self.view.frame segmentView:self.segmentView parentViewController:self delegate:self];
    self.contentView = content;
    [self.view addSubview:self.contentView];
}

- (NSInteger)numberOfChildViewControllers {
    return self.titles.count;
}


- (void)scrollPageController:(UIViewController *)scrollPageController childViewControllWillAppear:(UIViewController *)childViewController forIndex:(NSInteger)index {
    if (index == 0) {
        if (!self.isLogin) {
            MBLoginController *loginVC = [[MBLoginController alloc]init];
            [self presentViewController:loginVC animated:YES completion:nil];
        }
    }
}

- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    UIViewController<ZJScrollPageViewChildVcDelegate> *childVc = reuseViewController;
    
    if (!childVc) {
        childVc = self.childVcs[index];
    }
    
    return childVc;
}
- (BOOL)shouldAutomaticallyForwardAppearanceMethods {
    return NO;
}


#pragma mark - NSNotification
-(void)LoginState:(NSNotification *)noti {
    if ([[noti.userInfo objectForKey:@"isFlag"] isEqualToString:MBLoginFLag]) {
        [self.leftNavButton setImage:kImage(@"caIDAN") forState:UIControlStateNormal];
        [self.leftNavButton setTitle:@"" forState:UIControlStateNormal];
        self.rightNavButton.hidden = NO;
        self.isLogin = YES;
    }else {
        [self.leftNavButton setImage:kImage(@"") forState:UIControlStateNormal];
        [self.leftNavButton setTitle:@"登录" forState:UIControlStateNormal];
        self.rightNavButton.hidden = YES;
        self.isLogin = NO;
    }
}

-(void)CancelLogin:(NSNotification *)noti {
    [self.segmentView setSelectedIndex:1 animated:YES];
}

#pragma mark - event
-(void)leftNavButtonClick {
    if (![self.leftNavButton.currentTitle isEqualToString:@"登录"]) {
        [self.viewDeckController openSide:IIViewDeckSideLeft animated:YES];
    }else{
        MBLoginController *loginVC = [[MBLoginController alloc]init];
        [self presentViewController:loginVC animated:YES completion:nil];
    }
}

-(void)rightNavButtonClick:(UIButton *)button {
    [[UIApplication sharedApplication].keyWindow addSubview:self.menuView];
    MB_WeakSelf(self);
    self.menuView.shortVideoBlock = ^{
        MBShortVideoRecordConfig* videoConfig = [[MBShortVideoRecordConfig alloc]init];
        MBShortVideoController *vc = [[MBShortVideoController alloc]initWithConfigure:videoConfig];
        vc.MAX_RECORD_TIME = 11.0f;
        vc.entityType = MBShortVideoEntityTypeNormal;

        [weakself.navigationController pushViewController:vc animated:YES];
    };
    self.menuView.liveBlock = ^{
        [weakself checkLiveiLimits];
    };
//    MBShortVideoPublishController *vc = [[MBShortVideoPublishController alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)rightNavButtonLongClick:(UILongPressGestureRecognizer *)longGest {
    if (longGest.state == UIGestureRecognizerStateBegan) {
        MBShortVideoRecordConfig* videoConfig = [[MBShortVideoRecordConfig alloc]init];
        MBShortVideoController *vc = [[MBShortVideoController alloc]initWithConfigure:videoConfig];
        vc.MAX_RECORD_TIME = 30.0f;
        vc.entityType = MBShortVideoEntityTypeNormal;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)removeMenuClick {
    [self.menuView removeFromSuperview];
    self.menuView = nil;
}

-(void)shortVideoButtonLongClick:(UILongPressGestureRecognizer *)longGest {
    if (longGest.state == UIGestureRecognizerStateBegan) {
        [self removeMenuClick];
        MBShortVideoRecordConfig* videoConfig = [[MBShortVideoRecordConfig alloc]init];
        MBShortVideoController *vc = [[MBShortVideoController alloc]initWithConfigure:videoConfig];
        vc.MAX_RECORD_TIME = 30.0f;
        vc.entityType = MBShortVideoEntityTypeNormal;

        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - JXCategoryViewDelegate
//点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index{
    
}

//点击选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didClickSelectedItemAtIndex:(NSInteger)index{
    
}

//滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index{
    
}

//正在滚动中的回调
- (void)categoryView:(JXCategoryBaseView *)categoryView scrollingFromLeftIndex:(NSInteger)leftIndex toRightIndex:(NSInteger)rightIndex ratio:(CGFloat)ratio{
    
}

//自定义contentScrollView点击选中切换效果
- (void)categoryView:(JXCategoryBaseView *)categoryView didClickedItemContentScrollViewTransitionToIndex:(NSInteger)index {
}

#pragma mark - JXCategoryListContainerViewDelegate
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.titleArray.count;
}

- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    return [[MBHomeWaterfallController alloc] init];
}

#pragma mark - getter and setter
-(UIButton *)leftNavButton {
    if (_leftNavButton == nil) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:kImage(@"") forState:UIControlStateNormal];
        [button setTitle:@"登录" forState:UIControlStateNormal];
//        button.frame = (CGRect){{0,0},{40,40}};
        [button setTitleColor:Color_FF8000 forState:UIControlStateNormal];
        [button addTarget:self action:@selector(leftNavButtonClick) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = kFont(14);
        _leftNavButton = button;
    }
    return _leftNavButton;
}

-(UIButton *)rightNavButton {
    if (_rightNavButton == nil) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:kImage(@"sheyingji") forState:UIControlStateNormal];
        [button addTarget:self action:@selector(rightNavButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(rightNavButtonLongClick:)];
        longPress.minimumPressDuration = 1.0f;
        [button addGestureRecognizer:longPress];
        button.hidden = YES;
        _rightNavButton = button;
    }
    return _rightNavButton;
}

-(NSArray *)titleArray {
    if (_titleArray == nil) {
        _titleArray = @[@"关注",@"发现",@"同城",@"直播"];
    }
    return _titleArray;
}
-(MBRightNavPullMenuView *)menuView {
    if (_menuView == nil) {
        _menuView = [MBRightNavPullMenuView nibView];
        _menuView.backgroundColor = [UIColor clearColor];
        _menuView.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
        UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeMenuClick)];
        [_menuView addGestureRecognizer:gest];
        
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(shortVideoButtonLongClick:)];
        longPress.minimumPressDuration = 1.0f;
        [_menuView.shortVideoButton addGestureRecognizer:longPress];
        
    }
    return _menuView;
}

@end
